<template>
  <div class="login-container">
    <el-card class="login-card" shadow="hover">
      <div class="header">
        <h2>豆酱观影分析平台</h2>
      </div>

      <el-form
          ref="loginForm"
          :model="loginForm"
          :rules="loginRules"
          label-width="0"
          class="form"
      >
        <el-form-item prop="email">
          <el-input
              v-model="loginForm.email"
              placeholder="请输入邮箱"
              prefix-icon="el-icon-user"
              autocomplete="off"
          >
            <i slot="prefix" class="el-icon-s-promotion"></i>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
              type="password"
              v-model="loginForm.password"
              placeholder="请输入密码"
              prefix-icon="el-icon-lock"
              autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
              type="primary"
              class="full-width"
              @click="submitLogin"
          >
            登录
          </el-button>
        </el-form-item>
        <div class="register-link">
          还没有账号？<el-button type="text" @click="goToRegister">立即注册</el-button>
        </div>
        <div class="forgot-password-link">
          <el-button type="text" @click="showForgotPasswordDialog">忘记密码？</el-button>
        </div>
      </el-form>
    </el-card>
    
    <!-- 忘记密码对话框 -->
    <el-dialog
      v-model="forgotPasswordVisible"
      title="重置密码"
      width="400px"
      :before-close="closeForgotPasswordDialog"
    >
      <el-form :model="forgotPasswordForm" :rules="forgotPasswordRules" ref="forgotPasswordForm" label-width="80px">
        <el-form-item label="邮箱" prop="email">
          <div class="email-input-group">
            <el-input
              v-model="forgotPasswordForm.email"
              placeholder="请输入注册时的邮箱"
            />
            <el-button 
              @click="sendResetCode" 
              :disabled="resetCountdown > 0 || !forgotPasswordForm.email"
              size="small"
              type="primary"
            >
              {{ resetCountdown > 0 ? `${resetCountdown}s` : '发送验证码' }}
            </el-button>
          </div>
        </el-form-item>
        
        <el-form-item label="验证码" prop="code">
          <el-input
            v-model="forgotPasswordForm.code"
            placeholder="请输入验证码"
            maxlength="6"
          />
        </el-form-item>
        
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            type="password"
            v-model="forgotPasswordForm.newPassword"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            type="password"
            v-model="forgotPasswordForm.confirmPassword"
            placeholder="请再次输入新密码"
            show-password
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeForgotPasswordDialog">取消</el-button>
          <el-button type="primary" @click="resetPassword" :loading="isResetting">重置密码</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { login, sendResetCode, resetPassword } from "@/api/login/Login.js";
import { useAuthStore } from '@/store/authStore';
import axios from 'axios';

export default {
  name: 'Login',
  data() {
    return {
      loginForm: {
        email: '',
        password: ''
      },
      loginRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱格式', trigger: ['blur', 'change'] }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '密码长度至少为6位', trigger: 'blur' }
        ]
      },
      // 忘记密码相关数据
      forgotPasswordVisible: false,
      forgotPasswordForm: {
        email: '',
        code: '',
        newPassword: '',
        confirmPassword: ''
      },
      forgotPasswordRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱格式', trigger: ['blur', 'change'] }
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { len: 6, message: '验证码为6位数字', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, message: '密码长度至少为6位', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请确认密码', trigger: 'blur' },
          { validator: this.validateConfirmPassword, trigger: 'blur' }
        ]
      },
      resetCountdown: 0,
      isResetting: false
    };
  },
  methods: {
    submitLogin() {
      const authStore = useAuthStore();
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          // 调用登录接口
          login(this.loginForm)
              .then(response => {
                console.log('登录响应:', response.data);
                if (response.data && response.data !== false) {
                  // 登录成功，response.data 是用户信息
                  console.log('用户信息:', response.data);
                  console.log('用户ID:', response.data.id);
                  this.$message.success('登录成功');
                  authStore.login(response.data); // 存储完整的用户信息
                  this.$router.push('/home');
                } else {
                  this.$message.warning('邮箱或密码不正确');
                }
              })
              .catch(() => {
                this.$message.error('登录失败，请稍后重试');
              });
        } else {
          this.$message.warning('请检查输入内容');
          return false;
        }
      });
    },
    goToRegister() {
      this.$router.push('/register');
    },
    showForgotPasswordDialog() {
      this.forgotPasswordVisible = true;
      this.resetCountdown = 0; // 重置倒计时
    },
    closeForgotPasswordDialog() {
      this.forgotPasswordVisible = false;
      this.$refs.forgotPasswordForm.resetFields();
    },
    async sendResetCode() {
      if (!this.forgotPasswordForm.email) {
        this.$message.warning('请先输入邮箱');
        return;
      }
      
      // 立即开始倒计时，防止重复点击
      this.startCountdown();
      this.isResetting = true;
      
      try {
        await sendResetCode(this.forgotPasswordForm.email);
        this.$message.success('验证码已发送，请查收邮件');
      } catch (error) {
        console.error('发送验证码失败:', error);
        // 显示具体的错误信息
        if (error.response && error.response.status === 400) {
          const errorMessage = error.response.data || '发送失败';
          this.$message.error(errorMessage);
        } else {
          this.$message.error('发送验证码失败，请稍后重试');
        }
        // 发送失败时重置倒计时，允许重新发送
        this.resetCountdown = 0;
      } finally {
        this.isResetting = false;
      }
    },
    startCountdown() {
      this.resetCountdown = 60;
      const timer = setInterval(() => {
        this.resetCountdown--;
        if (this.resetCountdown <= 0) {
          clearInterval(timer);
        }
      }, 1000);
    },
    validateConfirmPassword(rule, value, callback) {
      if (value !== this.forgotPasswordForm.newPassword) {
        callback(new Error('两次输入的密码不一致'));
      } else {
        callback();
      }
    },
    async resetPassword() {
      this.$refs.forgotPasswordForm.validate(async valid => {
        if (valid) {
          this.isResetting = true;
          try {
            await resetPassword(this.forgotPasswordForm);
            this.$message.success('密码重置成功，请重新登录');
            this.closeForgotPasswordDialog();
            this.loginForm.email = this.forgotPasswordForm.email; // 使用重置后的邮箱进行登录
            this.submitLogin(); // 触发登录
          } catch (error) {
            this.$message.error('密码重置失败，请稍后重试');
          } finally {
            this.isResetting = false;
          }
        } else {
          this.$message.warning('请检查输入内容');
          return false;
        }
      });
    }
  }
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #d0eaff, #f0f8ff);
  padding: 20px;
}
.login-card {
  width: 100%;
  max-width: 400px;
  padding: 30px;
  border-radius: 12px;
}
.header {
  text-align: center;
  margin-bottom: 20px;
}
.header h2 {
  font-weight: bold;
  font-size: 1.75rem;
  color: #165dff;
}
.full-width {
  width: 100%;
}
.register-link {
  margin-top: 10px;
  text-align: center;
  font-size: 0.9rem;
}

.forgot-password-link {
  margin-top: 5px;
  text-align: center;
  font-size: 0.9rem;
}

.email-input-group {
  display: flex;
  gap: 10px;
  align-items: center;
}

.email-input-group .el-input {
  flex: 1;
}

.email-input-group .el-button {
  white-space: nowrap;
  min-width: 100px;
}

.dialog-footer {
  text-align: right;
}
</style>
